package com.why.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liha
 * @since 2021/10/16
 */
public class JwtUtils {

	static String security_key = "SDH$%&#$ADG#$^SGD";

	public static void main(String[] args) {

	//	Result<String> result = new Result<>(100, "aa", "cc");

	//	createToken("张二哥",30, JSONUtil.toJsonStr(result));

	String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiLlvKDkuozlk6UiLCJuYmYiOjE2NTM4NzM1ODEsImpzb24iOiJ7XCJjb2RlXCI6MTAwLFwiZXJySW5mb1wiOlwiYWFcIixcImpkYXRhXCI6XCJjY1wifSIsImV4cCI6MTY1Mzg3NTM4MSwiaWF0IjoxNjUzODczNTgxfQ.JLWHp3Q5uoKXxugZrKX3CFgfIyXnmtb9Tu3VzLnEy2I";
		parseToken(token);
	}

	/**
	 *
	 * @param subject  主题
	 * @param expireTime  有效期分钟
	 * @param jsonExtend  扩展的接送信息
	 * @return
	 */
	public static  String createToken(String subject,int expireTime,String jsonExtend) {
		DateTime now = DateTime.now();
		DateTime newTime = now.offsetNew(DateField.MINUTE, expireTime);

		Map<String, Object> payload = new HashMap<String, Object>();
		//签发时间
		payload.put(JWTPayload.ISSUED_AT, now);
		//过期时间
		payload.put(JWTPayload.EXPIRES_AT, newTime);
		//生效时间
		payload.put(JWTPayload.NOT_BEFORE, now);

		payload.put(JWTPayload.SUBJECT, subject);
		//载荷
		payload.put("json", jsonExtend);

		String token = JWTUtil.createToken(payload, security_key.getBytes());
		System.out.println("create token is " + token);
		return token;
	}

	public static void parseToken(String token){
		JWT jwt = JWTUtil.parseToken(token);
		boolean verifyKey = jwt.setKey(security_key.getBytes()).verify();
		JSONObject payloads = jwt.getPayloads();
		System.out.println("suject is " + jwt.getPayload(JWTPayload.SUBJECT));
		System.out.println("suject is " + jwt.getPayload("json"));

		boolean verifyTime = jwt.validate(0);
		System.out.println(verifyTime);
	}

	public static String getSubject(String token){
		System.out.println("got token is " + token);
		JWT jwt = JWTUtil.parseToken(token);
		boolean verifyKey = jwt.setKey(security_key.getBytes()).verify();
		if (!verifyKey){
			return "";
		}
		boolean verifyTime = jwt.validate(0);
		if (!verifyTime){
			return "";
		}
		JSONObject payloads = jwt.getPayloads();
		return (String) jwt.getPayload(JWTPayload.SUBJECT);
	}

	public static String getJson(String token){
		JWT jwt = JWTUtil.parseToken(token);
		boolean verifyKey = jwt.setKey(security_key.getBytes()).verify();
		if (!verifyKey){
			return "";
		}
		boolean verifyTime = jwt.validate(0);
		if (!verifyTime){
			return "";
		}
		JSONObject payloads = jwt.getPayloads();
		return (String) jwt.getPayload("json");
	}

}
